import time,json

from nebula3.Config import SessionPoolConfig
from nebula3.gclient.net.SessionPool import SessionPool
from flask import Flask, request, jsonify
from flask_cors import CORS
from urllib.parse import unquote
from gmssl import sm3

NEBULA_IP = '127.0.0.1'
NEBULA_PORT = 9669
NEBULA_USER = 'root'
NEBULA_PSW = 'root'
NEBULA_SPACE = 'portrait'

API_PORT = 9876

app = Flask(__name__)
CORS(app)

def get_session_pool(ip=NEBULA_IP, port=NEBULA_PORT, account=NEBULA_USER, psw=NEBULA_PSW, space=NEBULA_SPACE):
    config = SessionPoolConfig()
    # session_pool = SessionPool("root", "nebula", "test", [(ip, port)])
    session_pool = SessionPool(account, psw, space, [(ip, port)])
    assert session_pool.init(config)
    return session_pool

@app.route('/picture/getMerchantPictureById', methods=['POST'])
def mchtPortrait():
    picId = request.get_json()['pictureId']
    sess = get_session_pool()
    data = sess.execute(f'MATCH (v) where id(v) == "{picId}" return v').as_data_frame().to_dict('list')
    if not data:
        return {
            'code': 1,
            'message': '商户画像未建立',
            'data': None
        }
    return {
        'code': 200,
        'message': 'success',
        'data': data['v'][0]['tags']
    }

@app.route('/picture/getPictureById', methods=['POST'])
def userPortrait():
    picId = request.get_json()['pictureId'].strip()
    queryByMobile = len(picId) == 11
        
    sess = get_session_pool()
    
    result = {
        'code': 1,
        'data': None,
        'message': '该用户画像未建立'
    }
    
    if queryByMobile:
        # body_str = json.dumps(picId)
        msg_list = [i for i in bytes(picId.encode('UTF-8'))]
        mobile = sm3.sm3_hash(msg_list).upper()
        print(mobile)
        res = sess.execute(f'MATCH (m)-[e:mobile_belongsto]->(u) where id(m) == "{mobile}" return u').as_data_frame().to_dict('list')
        if not res:
            return result
        picId = res['u'][0]['vid']
        
    
    user_info= sess.execute(f'MATCH (v) where id(v) == "{picId}" return v')
    # data = sess.execute_json
    print(user_info.as_data_frame().to_dict())
    if not user_info.as_data_frame().to_dict(orient='records'):
        return result
    
    result = user_info.as_data_frame().to_dict(orient='records')[0]['v']['tags']
    cards = sess.execute(f'MATCH (u)-[e:has_card]->(c) where id(u) == "{picId}" return id(c)')
    card_ids = cards.as_data_frame().to_dict(orient='list')['id(c)']
    
    cards_info = sess.execute(f'MATCH (v) where id(v) IN {json.dumps(card_ids)} return v').as_data_frame().to_dict(orient='list')
    cards_info_out = {}
    
    for ele in cards_info['v']:
        cards_info_out[ele['vid']] = ele['tags']
    result['card'] = cards_info_out
    out = {
        'code': 200,
        'message': 'success',
        'data': result
    }
    return jsonify(out)


session_pool = get_session_pool()

@app.route('/', methods=['GET'])
def get_data():
    
    q = request.args.get('q')
    if not q:
        return {}
    print(unquote(q))
    orient = request.args.get('orient', 'list')
    
    # return json.loads(session_pool.execute_json(q))
    
    resp = session_pool.execute((q))
    if not resp.is_succeeded():
        return jsonify({
          'err': resp.error_msg()
        })
    data = resp.as_data_frame().to_dict(orient=orient)
    
    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=API_PORT)